import time
from threading import Thread
from autoTask.Base import Login, ThrowError
from common.logger.log import log_
from request.remote import code as remote_code
from config.Setting import Setting
from autoTask.tools import Slider, Picture


class PinDuoDuo(Login):

    def __init__(self, account, password):
        super().__init__(account, password)

    def listen_init(self):
        action_map = {
            'https://mms.pinduoduo.com/janus/api/auth': self.auth_check,
            'https://mms.pinduoduo.com/janus/api/logout': self.logout_check,
            'https://apiv2.pinduoduo.net/api/phantom/obtain_captcha': self.slider_check,
            'https://apiv2.pinduoduo.net/api/phantom/user_verify': self.user_verify,
        }
        return action_map

    def login_step(self):
        log_.info('执行登录操作')
        page, hand = self.page, self.hand
        page.get('https://mms.pinduoduo.com/login')
        hand.click('tx:账号登录')
        hand.fill(self.account, 'x://input[@id="usernameId"]')
        hand.fill(self.password, 'x://input[@id="passwordId"]')
        hand.click('x://div[@class="info-content"]/button')

    def logout_step(self):
        log_.info('执行退出操作')
        page = self.page
        page.get('https://mms.pinduoduo.com/janus/api/logout')

    def login(self):
        page = self.page
        url = 'https://mms.pinduoduo.com/home'
        page.get(url)
        if page.url == url:
            log_.info('已登录, 检测账号是否相同')
            Thread(target=self.account_same).start()
        else:
            log_.info('未登录')
            Thread(target=self.login_step).start()

    def account_same(self):
        page = self.page
        name = page.ele('x://div[@class="user-name-id"]/span')
        if not name:
            self.stop('不可预知错误')
        if name.text == self.account:
            log_.info('账号相同')
            self.login_state = True
            self.stop()
        else:
            log_.debug('账号不相同')
            Thread(target=self.logout_step).start()

    def logout_check(self, response):
        if response['success']:
            log_.info('退出账号成功')
            Thread(target=self.login_step).start()
        else:
            raise ThrowError('退出账号失败')

    def auth_check(self, response):
        log_.debug(response)
        if response['success']:
            log_.info('登录成功')
            self.login_state = True
            self.stop()
            return
        errCode = response['errorCode']
        errMsg = response['errorMsg']
        if errCode == 402:
            self.stop('账号密码错误')
        elif errMsg == '需要手机验证' or errCode == 2000020:  # 手机验证码
            phone = response['result']
            Thread(target=self.phone_code, args=(phone, )).start()
        elif errMsg == '验证码错误或已失效' or errCode == 4000003:
            self.stop(errMsg)
        else:
            self.stop(errMsg)

    def phone_code(self, phone=None):
        page, hand = self.page, self.hand
        self.stop('需要验证码')
        # hand.click('tx:获取验证码')
        # try:
        #     self.tid = remote_code.add(phone)
        #     print(f'{Setting.REMOTE_SEVER_API}/{self.tid}')  # 无api, 暂控制台输出
        #     Thread(target=self.phone_code_step).start()
        # except Exception as e:
        #     self.stop(e)

    def phone_code_step(self, count=0):
        max_count = 30
        if count >= max_count:
            self.stop('等待时间过长, 验证码失效, 任务关闭')
        if self.tid is None:
            self.stop('tid 为空')
        tid = self.tid
        time.sleep(10)
        log_.debug(f'{tid}, Cur: {count+1}, Max: {max_count}')
        page, hand = self.page, self.hand
        try:
            code = remote_code.get(tid)
        except Exception as e:
            self.stop(e)
            return
        if code:
            hand.fill(code, 'x://div[@class="vertify-code"]//input')
            hand.click('x://section[@class="verify-phone-container"]/button')
            return
        Thread(target=self.phone_code_step, args=(count+1,)).start()

    def user_verify(self, response):
        log_.debug(f'第{self.slider_tries}次滑块验证尝试, 验证 {response["result"]}')

    def slider(self):
        page, hand = self.page, self.hand
        save = Picture.Save()
        bg_img_path = save.bytesTo('bg.png', page.ele('x://img[@class="slider-img-bg"]').get_src())
        slice_img_path = save.bytesTo('slice.png', page.ele('x://img[@class="slider-item"]').get_src())
        distance = Slider.Contrast(bg_img_path, slice_img_path).distance(show=False)
        btn = page.ele('x://div[@class="slide-button-wrapper"]')
        hand.drag_x(btn, distance - 28)


if __name__ == '__main__':
    # res = PinDuoDuo('赫巴兹官旗强', 'Hbz123456').action()
    # res = PinDuoDuo('赫巴兹家居官方旗舰店数据1', 'Yzt123456').action()
    res = PinDuoDuo('赫巴兹旗舰店优', 'Zty12133').action()
    # res = PinDuoDuo('123456', '123456').action()
    print(res)
